package com.weichuanbo.xwdz.app.utils;

import android.content.Context;
import android.text.TextUtils;

import com.weichuanbo.xwdz.app.Common;
import com.weichuanbo.xwdz.mvp.model.entity.UserBean;

import java.io.UnsupportedEncodingException;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *
 * Created by ssy on 2018/9/3 18:03
 * E-Mail ：1161209667@qq.com
 * 功能：MD5签名处理核心文件，不需要修改
 * 说明：
 */

public class SignUtil {

    private static final String TAG = SignUtil.class.getSimpleName();
    private static Context mContext;
    private static String token;

    /**
     * @param content
     * @param charset
     * @return
     * @throws SignatureException
     * @throws UnsupportedEncodingException
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    public static void init(Context context) {
        mContext = context;
        token = reGetToken();
    }

    /**
     * 除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map paraFilter(Map<String, Object> sArray) {

        Map result = new HashMap();

        if (sArray == null || sArray.size() <= 0) {
            return result;
        }

        for (String key : sArray.keySet()) {
            String value = sArray.get(key).toString();
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
                    || key.equalsIgnoreCase("sign_type")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, Object> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i).trim();
            String value = params.get(key).toString();

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "#";
            }
        }
        return prestr;
    }

    public static Map addSign(Map paramsMap){
        paramsMap.put("sign",getSign(paramsMap));
        return paramsMap;
    }

    /**
     * 根据传入的请求参数  得到最终的sign
     *
     * @param params
     * @return
     */
    public static String getSign(Map params) {
        params.putAll(getCommonMap());
        params = SignUtil.paraFilter(params);
        String text = SignUtil.createLinkString(params);
//        text="appId=shj123123&"+text+"&appKey=shj321321";//拼接要进行加密的参数(测试环境)
        text = "appId=miwan#" + text + "#key=c04d027946ec8451c630a0518a223904";//拼接要进行加密的参数(正式环境)
        return MD5Util.md5(MD5Util.md5(text));
    }

    /**
     * 配置公共参数
     *
     * @return
     */
    private static Map<String, String> getCommonMap() {
        Map<String, String> params = new HashMap<>();
        long timestamp = Common.serverTime < 1534077114 ? System.currentTimeMillis() / 1000 : Common.serverTime;
        params.put("timestamp", timestamp + "");
        params.put("device", "Android");
        if (TextUtils.isEmpty(token))
            token = reGetToken();
        if (!TextUtils.isEmpty(token))
            params.put("token", token);
        return params;
    }

    public static String reGetToken() {
        Object bean = SaveBeanUtil.getBean(mContext, Common.Const.VIPINFO);
        if (bean == null || TextUtils.isEmpty(bean.toString()))
            return null;
        return ((UserBean) bean).getToken();
    }
}